package com.ncmmall.api.apis.mall;

import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.params.OrderAfterSaleDTO;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.order.OrderAfterSaleApplication;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.marketing.gift.GiftActivity;
import com.ncmmall.domain.business.order.OrderDetail;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSale;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleCheckRecord;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSaleImage;
import com.ncmmall.domain.business.order.aftersale.QOrderAfterSale;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author linxs
 * @Description: 售后售后订单模块
 * @Date: 2019-07-23 14:08
 */
@RestController
@RequestMapping(value = "/orderAfterSale")
public class OrderAfterSaleApi {

    private final Logger logger = LoggerFactory.getLogger(OrderAfterSaleApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private OrderAfterSaleApplication afterSaleApplication;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 售后订单列表
     *
     * @param request
     * @param pageNo
     * @param pageSize
     * @param status
     * @return
     */
    @GetMapping("/list")
    public Result list(HttpServletRequest request, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "0") int status) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
            Map<String, Object> params = Maps.newHashMap();
            params.put("id", member.getId());

            String hql = builderHql("select o from OrderAfterSale o where o.member.id = :id ", params, status);
            QueryPage<OrderAfterSale> page = queryChannelService.findPage(hql, pageRequest.setParams(params), OrderAfterSale.class);
            for (OrderAfterSale afterSale : page.getResult()) {

                for (OrderDetail detail : afterSale.getOrder().getDetails()) {
                    detail.setDefaultImage(storeDomain + "/uploads/" + detail.getDefaultImage());
                }

                for (OrderAfterSaleImage orderAfterSaleImage : afterSale.getImages()) {
                    orderAfterSaleImage.setName(storeDomain + "/uploads/" + orderAfterSaleImage.getName());
                }

                //赠品活动订单
                if (afterSale.getOrder().getMarketingType() == 1) {
                    List<Goods> giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", afterSale.getOrder().getGiftActivity().getId()), Goods.class);

                    GiftActivity giftActivity = afterSale.getOrder().getGiftActivity();
                    giftActivity.setGiftGoodses(giftGoodses.stream().map(input -> {
                        Map<String, Object> data = new HashMap<>();
                        data.put("id", input.getId());
                        data.put("name", input.getName());
                        data.put("defaultImage", storeDomain + "/uploads/" + input.getDefaultImage());
                        return data;
                    }).collect(Collectors.toList()));
                    afterSale.getOrder().setGiftActivity(giftActivity);
                }

            }

            return result.ok().inject(ImmutableMap.of("page", page));

        } catch (Exception e) {
            logger.error("[售后订单列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }

    /**
     * 协商记录
     *
     * @return
     */
    @GetMapping("/checkList")
    public Result checkList(HttpServletRequest request, @RequestParam("id") long id) {
        Result result = new Result();
        try {
            List<OrderAfterSaleCheckRecord> afterSaleCheckRecords = queryChannelService.findAll("select a from OrderAfterSaleCheckRecord a where a.afterSale.id = :aid order by a.createTime desc ", ImmutableMap.of("aid", id), OrderAfterSaleCheckRecord.class);

            return result.ok().inject(afterSaleCheckRecords);

        } catch (Exception e) {
            logger.error("[售后协商列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }

    /**
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Result detail(HttpServletRequest request, @RequestParam long id) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(id), OrderAfterSale.class);
            for (OrderAfterSaleImage orderAfterSaleImage : afterSale.getImages()) {
                orderAfterSaleImage.setName(storeDomain + "/uploads/" + orderAfterSaleImage.getName());
            }

            for (OrderDetail detail : afterSale.getOrder().getDetails()) {
                detail.setDefaultImage(storeDomain + "/uploads/" + detail.getDefaultImage());
            }

            //赠品活动订单
            if (afterSale.getOrder().getMarketingType() == 1) {
                List<Goods> giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", afterSale.getOrder().getGiftActivity().getId()), Goods.class);

                GiftActivity giftActivity = afterSale.getOrder().getGiftActivity();
                giftActivity.setGiftGoodses(giftGoodses.stream().map(input -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("id", input.getId());
                    data.put("name", input.getName());
                    data.put("defaultImage", storeDomain + "/uploads/" + input.getDefaultImage());
                    return data;
                }).collect(Collectors.toList()));
                afterSale.getOrder().setGiftActivity(giftActivity);
            }

            return result.ok().inject(afterSale);

        } catch (Exception e) {
            logger.error("[售后订单列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }

    /**
     * 申请售后
     *
     * @param request
     * @param params
     * @return
     */
    @PostMapping("/apply")
    public Result apply(HttpServletRequest request, @RequestBody OrderAfterSaleDTO params) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            OrderAfterSale sale = new OrderAfterSale();
            sale.setMember(member);
            sale.setAfterSaleReason(params.getReason());
            sale.setNote(params.getNote());
            sale.setOrderDetails(params.getOrderDetails());

            List<String> imagesData = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getImages());
            sale.setImages(Lists.transform(imagesData, new Function<String, OrderAfterSaleImage>() {
                @Nullable
                @Override
                public OrderAfterSaleImage apply(@Nullable String input) {
                    OrderAfterSaleImage image = new OrderAfterSaleImage();
                    image.setName(input);
                    return image;
                }
            }));

            sale = afterSaleApplication.apply(sale);

            return result.ok().inject(ImmutableMap.of("id", sale.getId()));

        } catch (Exception e) {
            logger.error("[售后订单列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }

    /**
     * 买家寄回
     *
     * @param request
     * @param params
     * @return
     */
    @PostMapping("/sendBack")
    public Result sendBack(HttpServletRequest request, @RequestBody OrderAfterSaleDTO params) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            afterSaleApplication.sendBack(params.getId(), params.getExpressCompany(), params.getExpressNo());

            return result.ok();

        } catch (Exception e) {
            logger.error("[售后订单列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }


    private String builderHql(String hql, Map<String, Object> params, int status) {
        if (status > 0) {
            hql += " and o.status = :status ";
            params.put("status", status);
        }

        hql += " order by o.createTime desc ";

        return hql;
    }

}
